package com.wxf.web;

import com.wxf.bean.Student;
import com.wxf.service.GradeService;
import com.wxf.service.StudentService;
import com.wxf.service.impl.GradeServiceImpl;
import com.wxf.service.impl.StudentServiceImpl;
import com.wxf.util.StudentStateEnum;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;

/**
 * 用于处理多个请求
 */
@WebServlet(urlPatterns = "/Educational/student/request")
public class StudentServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String type = req.getParameter("type");

        if("add".equals(type)){
            addStudentInfo(req,resp);
        }else if("getGradeList".equals(type)){
            getGradeList(req,resp);
        }else if("display".equals(type)){
            displayBeforeModifyStudentInfoServlet(req,resp);
        }else if("modify".equals(type)){
            modifyStudentInfo(req,resp);
        } else if("delete".equals(type)){
            deleteStudentInfo(req,resp);
        }else {
            getStudentListInfo(req, resp);
        }
    }

    protected void addStudentInfo(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 1-获取请求参数
        String stuNo = req.getParameter("stuNo");
        String stuName = req.getParameter("stuName");
        String gradeId = req.getParameter("gradeId");
        String sex = req.getParameter("sex");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String registered = req.getParameter("registered");
        String address = req.getParameter("address");
        String politics = req.getParameter("politics");
        String idNumber = req.getParameter("idNumber");
        String profession = req.getParameter("profession");
        String introduction = req.getParameter("introduction");

        // 2-封装成student对象
        Student student = new Student();
        student.setStuNo(stuNo);
        student.setStuName(stuName);
        student.setgId(Integer.parseInt(gradeId));
        student.setSex(Integer.parseInt(sex));
        student.setEmail(email);
        student.setPhone(phone);
        student.setRegistered(registered);
        student.setAddress(address);
        student.setPolitics(politics);
        student.setIdNumber(idNumber);
        student.setProfession(profession);
        student.setIntroduction(introduction);
        student.setState(StudentStateEnum.Normal.state);
        student.setRegdate(new Date());

        // 3-后台处理
        StudentService studentService = new StudentServiceImpl();
        int influenceRow = studentService.addStudentInfo(student);

        // 4-响应
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter pw = resp.getWriter();
        if(influenceRow==0){
            pw.println("<script>alert('添加失败');location.href='/Educational/student/request'</script>");
        }else{
            pw.println("<script>alert('添加成功');location.href='/Educational/student/request'</script>");
        }
    }

    protected void getStudentListInfo(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("Obtain student info servlet");
        // 1-获取请求参数
        // 1.1-获取查询学生名称、学号、性别参数
        String stuName = req.getParameter("stuName");
        String stuNo = req.getParameter("stuNo");
        String sex = req.getParameter("sex");
        sex=(sex==null?"-1":sex);
        // 1.2-获取客户端所选择的页码
        String pageIndex = req.getParameter("pageIndex");
        System.out.println(pageIndex);
        pageIndex=(pageIndex==null?"1":pageIndex);
        System.out.println(pageIndex);
        int pageNum = 5; // 每页显示条数
        //-----------------------------------------------------------------
        // 2-后台处理
        // 2.1-处理得到学生信息（全部信息和模糊查询）
        StudentService studentService = new StudentServiceImpl();
        List students = studentService.getStudentList(stuName,stuNo,Integer.parseInt(sex),Integer.parseInt(pageIndex),pageNum);
        // 2.2-获取总条数
        System.out.println(stuName+","+stuNo+","+sex);
        int totalDataNumber = studentService.getTotalDataNumber(stuName,stuNo,Integer.parseInt(sex));
        System.out.println(totalDataNumber);
        // 2.3-计算总页数
        int totalPageNum = (totalDataNumber%pageNum>0?1:0)+totalDataNumber/pageNum;

        // 3-响应
        // 后台给前台传值，要先存值
        req.setAttribute("studentList",students);
        req.setAttribute("stuName",stuName);
        req.setAttribute("stuNo",stuNo);
        req.setAttribute("sex",sex);
        req.setAttribute("currentPageIndex",pageIndex);
        req.setAttribute("totalDataNum",totalDataNumber);
        req.setAttribute("totalPageNum",totalPageNum);
        // 注意下面的路径不用加"/"，因为请求路径里有"Educational/student/",它会从这个路径下面去找资源
        // 如果加了"/"，表示从根目录（即web目录）去找资源
        req.getRequestDispatcher("list.jsp").forward(req,resp);
    }

    protected void getGradeList(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        GradeService gradeService = new GradeServiceImpl();
        List grades = gradeService.getGradeInfo();
        if(grades!=null){
            req.setAttribute("gradeList",grades);
            req.getRequestDispatcher("add.jsp").forward(req,resp);
        }
    }

    protected void displayBeforeModifyStudentInfoServlet(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
        // 当用户点击list.jsp中的修改时，跳转到add.jsp，在add.jsp中，首先要展示所选学生的信息
        // 1-获取请求参数
        String stuNo = req.getParameter("stuNumber");
        System.out.println(stuNo);
        // 2-后台处理
        StudentService studentService = new StudentServiceImpl();
        Student student = studentService.displayBeforeModifyStudentInfo(stuNo);
        System.out.println(student);
        if(student!=null){
            req.setAttribute("stuList",student);
            GradeService gradeService = new GradeServiceImpl();
            List gradeList = gradeService.getGradeInfo();
            req.setAttribute("gradeList",gradeList);
            req.getRequestDispatcher("edit.jsp").forward(req,resp);
        }else{
            resp.sendRedirect("/list.jsp");
        }
    }

    protected void modifyStudentInfo(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        // 1-获取请求参数
        req.setCharacterEncoding("utf-8");
        String stuNo = req.getParameter("stuNo");
        String stuName = req.getParameter("stuName");
        String gradeId = req.getParameter("gradeId");
        String sex = req.getParameter("sex");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String registered = req.getParameter("registered");
        String address = req.getParameter("address");
        String politics = req.getParameter("politics");
        String idNumber = req.getParameter("idNumber");
        String profession = req.getParameter("profession");
        String introduction = req.getParameter("introduction");
        String stuId = req.getParameter("stuId");

        // 2-封装成student对象
        Student student = new Student();
        student.setStuNo(stuNo);
        student.setStuName(stuName);
        student.setgId(Integer.parseInt(gradeId));
        student.setSex(Integer.parseInt(sex));
        student.setEmail(email);
        student.setPhone(phone);
        student.setRegistered(registered);
        student.setAddress(address);
        student.setPolitics(politics);
        student.setIdNumber(idNumber);
        student.setProfession(profession);
        student.setIntroduction(introduction);
        student.setState(0);
        student.setRegdate(new Date());
        student.setStuId(Integer.parseInt(stuId));

        // 后台处理
        StudentService studentService = new StudentServiceImpl();
        int influenceRow = studentService.modifyStudentInfo(student);

        // 响应
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter pw = resp.getWriter();
        if(influenceRow>0){
            pw.print("<script>alert('修改成功');location.href='/Educational/student/request'</script>");

        }else{
            pw.print("<script>alert('修改失败');location.href='/Educational/student/request?type=modify&stuList='"+student+"</script>");
        }
    }

    protected void deleteStudentInfo(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        // 1-获取请求参数
        String stuId = req.getParameter("stuId");
        System.out.println("stuId="+stuId);

        // 2-后台处理
        StudentService studentService = new StudentServiceImpl();
        int influenceRow = studentService.deleteStudentInfo(Integer.parseInt(stuId));

        // 3-响应
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter pw = resp.getWriter();
        if(influenceRow>0){
            pw.println("<script>alert('删除成功');location.href='/Educational/student/request'</script>");
        }else{
            pw.println("<script>alert('删除失败'>;location.href='/Educational/student/request'</script>");
        }
    }
}
